package cn.iot.controller;

import cn.iot.common.api.CommonResult;
import cn.iot.common.utils.StringUtils;
import cn.iot.domain.Floor;
import cn.iot.domain.Loudong;
import cn.iot.domain.Room;
import cn.iot.service.FloorService;
import cn.iot.service.RoomService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/room")
public class RoomController {

    @Autowired
    FloorService floorService;
    @Autowired
    RoomService roomService;

    @PostMapping("/getList")
    public CommonResult getList(Integer floorId, String roomName){
        LambdaQueryWrapper<Room> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(roomName),Room::getRoomName,roomName);
        queryWrapper.eq(Room::getFloorId,floorId);
        List<Room> list = roomService.list(queryWrapper);
        return CommonResult.success(list);
    }
    @PostMapping("/saveOrUpdate")
    public CommonResult saveOrUpdate(@RequestBody Room room){
        if(room.getId()==null){
            //新增 把楼层里的房间数加一
            Floor floor = floorService.getById(room.getFloorId());
            if(floor.getRoomNum()==null){
                floor.setRoomNum(1);
            }else {
                floor.setRoomNum(floor.getRoomNum()+1);
            }

            floorService.saveOrUpdate(floor);
        }
        roomService.saveOrUpdate(room);
        return CommonResult.success();
    }
    @DeleteMapping("/del/{id}")
    public CommonResult deleteById(@PathVariable Integer id){
        Room room = roomService.getById(id);

        Floor floor = floorService.getById(room.getFloorId());
        floor.setRoomNum(floor.getRoomNum()-1);
        floorService.saveOrUpdate(floor);

        roomService.removeById(id);
        return CommonResult.success();
    }
}
